package com.jackeysun.app_common.http

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory


object ApiServeImpl {

    const val URL = "http://fanyi.youdao.com"

    private val mApiServe: ApiServe by lazy {
        val logging = HttpLoggingInterceptor()
        logging.setLevel(HttpLoggingInterceptor.Level.BODY)
        val client: OkHttpClient = OkHttpClient().newBuilder()
            .addInterceptor(logging)
            .build()

        Retrofit.Builder()
            .client(client)
            .baseUrl(URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiServe::class.java)
    }

    //    keyfrom=lewe518&key=70654389&type=data&doctype=json&version=1.1
    suspend fun translate(
        word: String,
        keyfrom: String = "lewe518",
        key: Int = 70654389,
        type: String = "data",
        doctype: String = "json",
        version: String = "1.1"
    ): Word? = withContext(Dispatchers.IO) {
        try {
            mApiServe.translate(keyfrom, key, type, doctype, version, word)
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}